﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace McCloudCore
{
    class McQueue
    {
        private MessageQueue queue;
        private Message msg;
        
        /// <summary>
        /// Instancia a fila (configurações em "roles")
        /// </summary>
        public McQueue()        
        {
            StorageAccountInfo accountQueue = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();            
            QueueStorage queueService = QueueStorage.Create(accountQueue);
            queueService.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
            queue = queueService.GetQueue("mcc");
            if (!queue.DoesQueueExist()) queue.CreateQueue();
            while (!queue.DoesQueueExist()) Thread.Sleep(10000);
        }

        public void put(Task task, int addTimeoutInSeconds)
        {                        
            string xmlString = null;
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Encoding = System.Text.Encoding.UTF8;
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(task.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                XmlWriter xw = XmlWriter.Create(ms, settings);
                x.Serialize(xw, task);
                xmlString = new System.Text.UTF8Encoding().GetString(ms.ToArray());
            }
            queue.Timeout = TimeSpan.FromSeconds(addTimeoutInSeconds);
            this.queue.PutMessage(new Message(xmlString), -1);
        }

        public Task get(int TimeoutDefaultInSeconds)
        {
            this.msg = this.queue.GetMessage(TimeoutDefaultInSeconds);
                        
            if (this.msg == null || this.msg.ContentAsBytes() == null)
            {
                Thread.Sleep(1000);
                return null;
            }
            XmlSerializer deserializer = new XmlSerializer(typeof(Task));
            MemoryStream ms = new MemoryStream(this.msg.ContentAsBytes());
            Task task = deserializer.Deserialize(ms) as Task;
            Log.WriteInformation("Timeout: " + this.msg.TimeNextVisible.Subtract(this.msg.InsertionTime).TotalSeconds.ToString() + " segundos");
            
            return task;
        }

        public void delete()
        {
            this.queue.DeleteMessage(this.msg);            

        }
    }
}
